﻿using System;
using System.Data;
using System.Data.Common;

namespace DataAccess

{
    public class DbConnector : IDbConnector
    {
        private DbConnection dataBaseConnection;

        private DbTransaction dataBaseTransaction;

        private Boolean disposed = false;

        private static System.Configuration.ConnectionStringSettings connectSettings = Configuration.DBConnection();

        private static DbProviderFactory dataBaseFactory = DbProviderFactories.GetFactory(connectSettings.ProviderName);

        public Boolean isBeginTransaction()
        {
            return dataBaseTransaction != null;
        }

        public DbConnection connection()
        {
            return dataBaseConnection;
        }

        public DbTransaction transaction()
        {
            return dataBaseTransaction;
        }

        public DbProviderFactory factory()
        {
            return DbConnector.dataBaseFactory;
        }

        public void openConnection()
        {
            if (this.dataBaseConnection == null)
            {
                dataBaseConnection = this.factory().CreateConnection();
                dataBaseConnection.ConnectionString = connectSettings.ConnectionString;
            }
            dataBaseConnection.Open();
        }

        public void closeConnection()
        {
            if (transaction() != null)
            {
                dataBaseTransaction.Dispose();
                dataBaseTransaction = null;
            }

            if (dataBaseConnection != null)
            {
                if (dataBaseConnection.State != ConnectionState.Closed)
                {
                    dataBaseConnection.Close();
                }
                dataBaseConnection.Dispose();
                dataBaseConnection = null;
            }
        }

        public void beginTransaction()
        {
            dataBaseTransaction = dataBaseConnection.BeginTransaction();
        }

        public void commit()
        {
            dataBaseTransaction.Commit();
        }

        public void rollback()
        {
            dataBaseTransaction.Rollback();
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(Boolean disposing)
        {
            if (disposed)
            {
                if (disposing)
                {
                    this.closeConnection();
                }
            }
            disposed = true;
        }

        //供GC调用的析构函数
        ~DbConnector()
        {
            Dispose(false);//释放非托管资源
        }
    }
}
